<template>
  <div class="flow-main" style="background: white">
    <el-form
      ref="ggFlowRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      :rules="rules"
      label-width="130px"
      label-position="right"
      @submit.prevent
    >
      <el-row :gutter="16">
        <el-col :span="14" v-if="!checkWidgetAuth('businessTypeId', 'hide')">
          <el-form-item label="业务类型" prop="TicketInfo.businessTypeId">
            <el-cascader
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="businessTypeIdPath"
              :options="businessTypeIdWidgetDropdownList"
              placeholder=""
              :clearable="true"
              :filterable="true"
              :show-all-levels="false"
              :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
              @change="onBusinessTypeIdValueChange"
              :disabled="checkWidgetAuth('businessTypeId', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{(formData.TicketInfo.businessTypeIdDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="14" v-if="!checkWidgetAuth('title', 'hide')">
          <el-form-item label="工单标题" prop="TicketInfo.title">
            <el-input
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.TicketInfo.title"
              type="text"
              placeholder=""
              :clearable="true"
              :show-word-limit="false"
              maxlength=""
              :disabled="checkWidgetAuth('title', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{formData.TicketInfo.title}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="14" v-if="!checkWidgetAuth('description', 'hide')">
          <el-form-item label="工单描述" prop="TicketInfo.description">
            <el-input
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.TicketInfo.description"
              type="textarea"
              placeholder="（问题详情）"
              :clearable="true"
              :show-word-limit="false"
              maxlength=""
              :disabled="checkWidgetAuth('description', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{formData.TicketInfo.description}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="14" v-if="!checkWidgetAuth('priority', 'hide')">
          <el-form-item label="优先级" prop="TicketInfo.priority">
            <el-radio-group
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.TicketInfo.priority"
              :disabled="checkWidgetAuth('priority', 'disabled')"
            >
              <el-radio
                v-for="item in priorityWidgetDropdownList"
                :key="item.itemId"
                :value="item.itemId"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
            <span class="input-item input-label" v-else>{{(formData.TicketInfo.priorityDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="14" v-if="!checkWidgetAuth('processorId', 'hide')">
          <el-form-item label="处理人" prop="TicketInfo.processorId">
            <el-select
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.TicketInfo.processorId"
              placeholder=""
              :clearable="true"
              :filterable="true"
              :disabled="checkWidgetAuth('processorId', 'disabled')"
              @visible-change="processorIdWidget.onVisibleChange"
            >
<!--              <el-option-->
<!--                v-for="item in processorIdWidgetDropdownList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id"-->
<!--              />-->
              <el-option
                v-for="item in processorIdWidgetDropdownList"
                :key="item.userId"
                :label="`${item.showName} ${item.mobile ? '(' + item.mobile + ')' : ''}`"
                :value="item.userId"
                :disabled="!item.mobile"
              >
              <!-- 自定义选项内容，左侧姓名，右侧手机号 -->
              <div class="option-content" style="display: flex; justify-content: space-between; width: 100%;">
                <span class="option-name">{{ item.showName }}</span>
                <span class="option-phone" v-if="item.mobile">{{ item.mobile }}</span>
<!--                <span class="option-no-phone" v-else>无手机号</span>-->
              </div>
              </el-option>
            </el-select>
            <span class="input-item input-label" v-else>{{(formData.TicketInfo.processorIdDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!checkWidgetAuth('expectSolveTime', 'hide')">
          <el-form-item label="预计解决时间" prop="TicketInfo.expectSolveTime">
            <el-date-picker
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.TicketInfo.expectSolveTime"
              type="date"
              placeholder=""
              :clearable="true"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled="checkWidgetAuth('expectSolveTime', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{formData.TicketInfo.expectSolveTime}}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ggFlow',
};
</script>

<script setup lang="ts">
import { useFlowAction } from '@/pages/workflow/handlerFlowTask/hook';
import { IProp } from '@/pages/workflow/handlerFlowTask/types';
import { FlowOperationController } from '@/api/flow';
import { SysFlowTaskOperationType } from '@/common/staticDict/flow';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useMessage, useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController, SysGlobalDictController ,SystemUserController} from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { TicketInfoData } from '@/api/generated/ticketInfoController';
import {GlobalDictItemCmeduController, TicketInfoController} from '@/api/generated';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';


const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const processDefinitionKey = 'ggFlow';

interface IGgFlowProps extends IProp {
  readOnly?: boolean | string;
  // 是否运行时任务
  isRuntimeTask?: boolean | string;
  // 是否草稿
  isDraft?: boolean | string;
  // 流程实例id
  processInstanceId?: string;
  // 抄送消息id
  messageId?: string;
  // 当前任务实例id
  taskId?: string;
  // 任务变量列表
  taskVariableList?: ANY_OBJECT[];
  // 委托人
  delegateUserId?: string;
};

const props = withDefaults(defineProps<IGgFlowProps>(), {
  readOnly: false,
  isRuntimeTask: false,
  isDraft: false,
  processInstanceId: undefined,
  taskId: undefined,
  messageId: undefined,
  taskVariableList: () => [],
});

const taskReadOnly = ref(true);

const ggFlowRef = ref();
// 表单数据定义
type GgFlowData = {
  TicketInfo: TicketInfoData;
};
// 表单数据
const formData = reactive<GgFlowData>({
  TicketInfo: {
    // 工单ID（主键）
    id: undefined,
    // 工单编号（如“CS-2024-09-000001”）
    ticketNo: undefined,
    // 业务类型ID（关联ticket_business_type表）
    businessTypeId: undefined,
    // 工单标题
    title: undefined,
    // 工单描述（问题详情）
    description: undefined,
    // 请求人ID（关联sys_user表；若为外部客户，关联customer表）
    requesterId: undefined,
    // 请求人类型：1-内部员工，2-外部客户
    requesterType: undefined,
    // 优先级：1-紧急，2-普通，3-低
    priority: undefined,
    // 工单状态：1-新建，2-待分配，3-处理中，4-待反馈，5-待审核，6-已解决，7-已关闭
    status: undefined,
    // 处理人ID（关联sys_user表）
    processorId: undefined,
    // 处理部门ID（关联sys_dept表）
    deptId: undefined,
    // 预计解决时间
    expectSolveTime: undefined,
    // 实际解决时间（状态变为“已解决”时自动填充）
    actualSolveTime: undefined,
    // 关闭原因（仅状态为“已关闭”时填写）
    closeReason: undefined,
    // 创建时间
    createTime: undefined,
    // 更新时间
    updateTime: undefined,
    // 创建人
    createUserId: undefined,
    // 更新人
    updateUserId: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TicketInfo.priority': [
    {required: true, message: '请输入优先级', trigger: 'blur'}
  ],
  'TicketInfo.processorId': [
    {required: true, message: '请输入处理人', trigger: 'blur'}
  ],
  'TicketInfo.expectSolveTime': [
    {required: true, message: '请输入预计解决时间', trigger: 'blur'}
  ],
  'TicketInfo.businessTypeId': [
    {required: true, message: '请输入业务类型', trigger: 'blur'}
  ],
  'TicketInfo.title': [
    {required: true, message: '请输入工单标题', trigger: 'blur'}
  ],
  'TicketInfo.description': [
    {required: true, message: '请输入工单描述', trigger: 'blur'}
  ],
});
const instance = getCurrentInstance();

const draftProcessInstanceId = ref<number | string | undefined>();
const draftTaskId = ref<number | string | undefined>();

const { preHandlerOperation, submitConsign } = useFlowAction(props);
const messageStore = useMessage();

const isStartFlow = computed(() => {
  return props.processInstanceId == null;
});

const isDraft = computed(() => {
  return typeof props.isDraft === 'string' ? props.isDraft === 'true' : props.isDraft;
});

const isRuntime = computed(() => {
  return typeof props.isRuntimeTask === 'string' ? props.isRuntimeTask === 'true' : props.isRuntimeTask;
});

// 撤销任务
const revokeTask = (operation: ANY_OBJECT) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm('是否撤销此任务？', '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(res => {
        return FlowOperationController.revokeHistoricTask({
          processInstanceId: props.processInstanceId,
          taskId: props.taskId,
          taskComment: '任务处理人撤销任务',
          taskVariableData: {
            latestApprovalStatus: operation.latestApprovalStatus
          },
          delegateUserId: props.delegateUserId
        });
      })
      .then(res => {
        resolve(res);
      })
      .catch(e => {
        return reject(e);
      });
  });
};
// 保存草稿
const handlerDraft = () => {
  return new Promise<void>((resolve, reject) => {
    let formData = getFormDataImpl();
    let params: ANY_OBJECT = {
      processDefinitionKey: processDefinitionKey,
      processInstanceId: props.processInstanceId || draftProcessInstanceId.value,
      ticketInfoDto: {
        ...formData.masterData
      },
      ...formData.relationData
    }
    TicketInfoController.startAndSaveDraftGgFlow(params).then(res => {
      ElMessage.success('草稿保存成功！');
      draftProcessInstanceId.value = (res.data as ANY_OBJECT).processInstanceId;
      draftTaskId.value = (res.data as ANY_OBJECT).taskId;
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
// 获取表单数据
const getFormDataImpl = () => {
  // 一对一、一对多、多对多关联数据
  let relationData: ANY_OBJECT = {};
  return {
    masterData: {
      ...formData.TicketInfo
    },
    relationData: relationData
  }
};
// 获取流程表单数据
const getMasterData = (operationType: string, assignee: string | Array<string> | undefined) => {
  let taskVariableData;
  if (Array.isArray(props.taskVariableList) && props.taskVariableList.length > 0) {
    taskVariableData = props.taskVariableList.reduce((retObj, item) => {
      if (item.variableType === 0) {
        // 固定值
        retObj[item.variableName] = item.variableValue;
      } else if (item.variableType === 1) {
        // 字段值
        retObj[item.variableName] = formData.TicketInfo[item.variableName]  == null ? '' : formData.TicketInfo[item.variableName];
      }
      return retObj;
    }, {});
  }
  // 会签操作设置多实例处理人集合
  assignee = (assignee && assignee !== '') ? (assignee as string).split(',') : undefined;
  if (operationType === StaticDict.SysFlowTaskOperationType.MULTI_SIGN) {
    if (taskVariableData == null) taskVariableData = {};
    taskVariableData.assigneeList = assignee;
  } else if (operationType === StaticDict.SysFlowTaskOperationType.SET_ASSIGNEE) {
    if (taskVariableData == null) taskVariableData = {};
    taskVariableData.appointedAssignee = Array.isArray(assignee) ? assignee.join(',') : undefined;
  }

  return {
    ...getFormDataImpl(),
    taskVariableData
  }
};
// 启动流程
const handlerStart = (operation: ANY_OBJECT, copyItemList: Array<ANY_OBJECT>, xml?: string | undefined) => {
  // 启动并保存草稿后再次提交
  if (draftProcessInstanceId.value != null && draftTaskId.value != null) {
    return handlerOperation(operation, copyItemList);
  }
  return new Promise<void>((resolve, reject) => {
    ggFlowRef.value.validate((valid: boolean) => {
      if (!valid) return reject();
      preHandlerOperation(operation, true, xml).then(res => {
        let formData = getMasterData(operation.type, (res || {}).assignee);
        let tempVariableData;
        if (operation.variableList != null && operation.variableList !== '') {
          if (typeof operation.variableList === 'string') {
            try {
              tempVariableData = JSON.parse(operation.variableList);
            } catch (e) {
              console.error(e);
            }
          } else {
            tempVariableData = operation.variableList;
          }
        }
        return TicketInfoController.startAndTakeUserTaskGgFlow({
          processDefinitionKey: processDefinitionKey,
          taskVariableData: {
            ...formData.taskVariableData,
            ...tempVariableData,
            latestApprovalStatus: operation.latestApprovalStatus
          },
          flowTaskCommentDto: {
            approvalType: operation.type
          },
          ticketInfoDto: {
            ...formData.masterData
          },
          ...formData.relationData,
          copyData: (copyItemList || []).reduce((retObj, item) => {
            retObj[item.type] = item.id;
            return retObj;
          }, {})
        });
      }).then(res => {
        ElMessage.success('启动成功！');
        resolve();
      }).catch(e => {
        reject(e);
      });
    });
  });
};
// 流程操作
const handlerOperation = (operation: ANY_OBJECT, copyItemList:Array<ANY_OBJECT>, xml?: string | undefined) => {
  return new Promise<void>((resolve, reject) => {
    ggFlowRef.value.validate(valid => {
      if (!valid) return reject();
      preHandlerOperation(operation, isDraft.value, xml).then(res => {
        // 加签、减签操作
        if (
          [
            SysFlowTaskOperationType.CO_SIGN,
            SysFlowTaskOperationType.SIGN_REDUCTION,
            SysFlowTaskOperationType.BFORE_CONSIGN,
            SysFlowTaskOperationType.AFTER_CONSIGN,
          ].includes(operation.type)
        ) {
          // 串行会签前后加签参数
          let before;
          if (
            operation.type === SysFlowTaskOperationType.BFORE_CONSIGN ||
            operation.type === SysFlowTaskOperationType.AFTER_CONSIGN
          ) {
            before = operation.type === SysFlowTaskOperationType.BFORE_CONSIGN;
          }
          return submitConsign((res || {}).assignee, operation.type === SysFlowTaskOperationType.CO_SIGN, before);
        }
        // 自由跳
        if (operation.type === StaticDict.SysFlowTaskOperationType.FREE_JUMP) {
          return FlowOperationController.freeJump({
            processInstanceId: props.processInstanceId,
            sourceTaskId: props.taskId,
            targetTaskKey: (res || {}).targetTaskKey,
            delegateAssignee: (res || {}).assignee,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 驳回操作
        if (
          operation.type === StaticDict.SysFlowTaskOperationType.REJECT ||
          operation.type === StaticDict.SysFlowTaskOperationType.REJECT_TO_TASK
        ) {
          return FlowOperationController.rejectRuntimeTask({
            processInstanceId: props.processInstanceId,
            taskId: props.taskId,
            targetTaskKey: (res || {}).targetTaskKey,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 驳回到起点
        if (operation.type === StaticDict.SysFlowTaskOperationType.REJECT_TO_START) {
          return FlowOperationController.rejectToStartUserTask({
            processInstanceId: props.processInstanceId,
            taskId: props.taskId,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 撤销操作
        if (operation.type === StaticDict.SysFlowTaskOperationType.REVOKE) {
          return revokeTask(operation);
        }
        let formData = getMasterData(operation.type, (res || {}).assignee);
        let params: ANY_OBJECT = {
          taskId: props.taskId || draftTaskId.value,
          processInstanceId: props.processInstanceId || draftProcessInstanceId.value,
          delegateUserId: props.delegateUserId,
          flowTaskCommentDto: {
            taskComment: (res || {}).message,
            approvalType: operation.type,
            delegateAssignee: operation.type === StaticDict.SysFlowTaskOperationType.TRANSFER ? (res || {}).assignee : undefined,
          },
          taskVariableData: {
            ...formData.taskVariableData,
            latestApprovalStatus: operation.latestApprovalStatus
          },
          copyData: (copyItemList || []).reduce((retObj, item) => {
            retObj[item.type] = item.id;
            return retObj;
          }, {})
        }
        // 非只读状态下，提交修改数据
        if (!taskReadOnly.value) {
          // 主表数据
          params.ticketInfoDto = {
            ...formData.masterData
          };
          // 关联数据
          params = {
            ...params,
            ...formData.relationData
          };
        }

        let tempVariableData;
        if (operation.variableList != null && operation.variableList !== '') {
          if (typeof operation.variableList === 'string') {
            try {
              tempVariableData = JSON.parse(operation.variableList);
            } catch (e) {
              console.error(e);
            }
          } else {
            tempVariableData = operation.variableList;
          }
        }
        if (tempVariableData != null) {
          params.taskVariableData = {
            ...params.taskVariableData,
            ...tempVariableData,
          };
        }

        return TicketInfoController.submitUserTaskGgFlow(params);
      }).then(res => {
        messageStore.reloadMessage();
        if (operation.type !== StaticDict.SysFlowTaskOperationType.CO_SIGN && operation.type !== StaticDict.SysFlowTaskOperationType.SIGN_REDUCTION) {
         ElMessage.success(operation.label + '成功！');
        }
        resolve();
      }).catch(e => {
        console.log(e);
      });
    });
  });
};

/**
 * 业务类型下拉数据获取函数
 */
const loadBusinessTypeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTicketBusinessType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 业务类型选中值改变
 */
const onBusinessTypeIdValueChange = (value) => {
  formData.TicketInfo.businessTypeId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 业务类型配置参数
const businessTypeIdOptions: DropdownOptions<DictData> = {
  loadData: loadBusinessTypeIdDropdownList,
  isTree: true,
};
// 业务类型选中数据
const businessTypeIdPath = ref<Array<string | number>>([]);
// 业务类型下拉组件
const businessTypeIdWidget = useDropdown(businessTypeIdOptions);
const { dropdownList: businessTypeIdWidgetDropdownList } = businessTypeIdWidget
/**
 * 优先级下拉数据获取函数
 */
const loadPriorityDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    let params = {
      dictCode: "priorityLevel",
    };
    SysGlobalDictController.listAll(params).then(res => {
      resolve({
        dataList: res.data.fullResultList,
      });
    }).catch(e => {
      reject(e);
    });
  });
  // return Promise.resolve({
  //   dataList: StaticDict.SysUserStatus.getList(),
  // });
};
// 优先级配置参数
const priorityOptions: DropdownOptions<DictData> = {
  loadData: loadPriorityDropdownList,
  isTree: false,
};
// 优先级下拉组件
const priorityWidget = useDropdown(priorityOptions);
const { dropdownList: priorityWidgetDropdownList } = priorityWidget
/**
 * 处理人下拉数据获取函数
 */
const loadProcessorIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    SystemUserController.getSelectlist(params).then(res => {
      console.log("====",res)
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 处理人配置参数
const processorIdOptions: DropdownOptions<DictData> = {
  loadData: loadProcessorIdDropdownList,
  isTree: false,
};
// 处理人下拉组件
const processorIdWidget = useDropdown(processorIdOptions);
const { dropdownList: processorIdWidgetDropdownList } = processorIdWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
/**
 * 重置过滤值
 */
const resetGgFlow = () => {
  refreshGgFlow();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetGgFlow();
};
const refreshGgFlow = () => {
  // 刷新段落
};
// 初始化流程表单
const initFormData = () => {
  if (!isStartFlow.value) {
    // 流程办理
    let params: ANY_OBJECT = {
      processInstanceId: props.processInstanceId,
      taskId: props.taskId,
      delegateUserId: props.delegateUserId,
    }
    let httpCall: ANY_OBJECT | null = null;
    if (isDraft.value) {
      // 草稿数据
      httpCall = FlowOperationController.viewDraftData({
        processDefinitionKey: processDefinitionKey,
        processInstanceId: props.processInstanceId
      });
    } else if (props.messageId != null) {
      // 抄送消息
      httpCall = FlowOperationController.viewCopyBusinessData({
        messageId: props.messageId
      });
    } else {
      httpCall = (props.taskId && isRuntime.value) ? TicketInfoController.viewTaskBusinessDataGgFlow(params) : TicketInfoController.viewHistoricTaskBusinessDataGgFlow(params)
    }
    httpCall.then(res => {
      formData.TicketInfo = { ...res.data };
      businessTypeIdWidget.onVisibleChange(true).then(res => {
        // TODO: 获取级联选中路径
        businessTypeIdPath.value = findTreeNodePath(res, formData.TicketInfo.businessTypeId);
      }).catch(e => {
        // TODO: 异常处理
        console.error(e);
      });
      priorityWidget.onVisibleChange(true).catch(e => {console.error(e)});
      processorIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
      refreshGgFlow();
    }).catch(e => {
      // 异常处理
      console.log(e);
    });
  } else {
    // 启动流程
    businessTypeIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      businessTypeIdPath.value = findTreeNodePath(res, formData.TicketInfo.businessTypeId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    priorityWidget.onVisibleChange(true).catch(e => {console.error(e)});
    processorIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    refreshGgFlow();
  }
};

const formAuth = ref<ANY_OBJECT>({});
const formAuthData = computed(() => {
  return (formAuth.value || {}).pc;
});

const checkWidgetAuth = (variableName: string, authType) => {
  console.log(formAuthData.value, variableName);
  if (formAuthData.value == null || formAuthData.value[variableName] == null) {
    return false;
  }
  let authItem = formAuthData.value[variableName];
  if (authType === 'disabled') {
    return authItem.disabled;
  } else if (authType === 'hide') {
    return authItem.hide;
  }
  return false;
};

const viewTaskFormKey = () => {
  return new Promise((resolve, reject) => {
    FlowOperationController.viewTaskFormKey({
      processDefinitionKey: processDefinitionKey,
      processInstanceId: props.processInstanceId,
      taskId: props.taskId
    })
      .then(res => {
        let temp = JSON.parse(res.data);
        taskReadOnly.value = temp.readOnly == null ? true : temp.readOnly;
        formAuth.value = temp.formAuth;
        Object.keys(formAuth.value || {}).forEach(key => {
          let formAuthItem = formAuth.value[key];
          Object.keys(formAuthItem).forEach(subKey => {
            let authItem = formAuthItem[subKey];
            if (authItem && authItem != null && authItem !== '') {
              formAuthItem[subKey] = authItem.split(',').map(item => parseInt(item));
            } else {
              formAuthItem[subKey] = [0, 0];
            }
            let disabled = formAuthItem[subKey][0] === 1;
            let hide = formAuthItem[subKey][1] === 1;
            formAuthItem[subKey].disabled = disabled;
            formAuthItem[subKey].hide = hide;
          });
        });
        resolve(res);
      })
      .catch(e => {
        reject(e);
      });
  });
};

onMounted(() => {
  viewTaskFormKey().then(() => {
    initFormData();
  }).catch(e => {
    console.log(e);
  });
});

defineExpose({
  handlerStart,
  handlerOperation,
  handlerDraft,
  initFormData,
  getMasterData,
});
</script>

<style scoped>
.flow-main {
  display: flex;
  flex-direction: column;
  background: #F6F7F9;
}
</style>
